package com.heima.article.service.impl;

import com.heima.article.service.ArticleBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.vos.LoadArticleBehaviorVO;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-09-23 10:16
 */
@Service
@Slf4j
public class ArticleBehaviorServiceImpl implements ArticleBehaviorService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public LoadArticleBehaviorVO loadArticleBehavior(ArticleInfoDto dto) {

        LoadArticleBehaviorVO loadArticleBehaviorVO = new LoadArticleBehaviorVO();

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null || user.getId() == null) {
            return loadArticleBehaviorVO;
        }
        String articleId = dto.getArticleId().toString();
        String userId = user.getId().toString();
        String authorId = dto.getAuthorId().toString();
        //获取当前点赞
        BoundSetOperations<String, String> set = stringRedisTemplate.
                boundSetOps(BehaviorConstants.LIKE_BEHAVIOR + articleId);
        //点赞
        //判断是否点赞
        Boolean member = set.isMember(userId);
        if (member != null && member) {
            //已经存在
            loadArticleBehaviorVO.setIslike(true);
        }

        //判断是否关注

        BoundSetOperations<String, String> setFollow = stringRedisTemplate.
                boundSetOps(BehaviorConstants.APUSER_FOLLOW_RELATION + userId);
        member = setFollow.isMember(authorId);
        if (member != null && member) {
            //已经存在
            loadArticleBehaviorVO.setIsfollow(true);
        }

        return loadArticleBehaviorVO;
    }
}
